/*
 * Copyright (C) 2018 Sergej Shafarenka, www.halfbit.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ohos.magnetx;

import magnet.Instance;
import magnet.SelectorFilter;
import ohos.data.preferences.Preferences;

import static com.ohos.magnetx.FeatureSelector.FEATURE_SELECTOR;

/**
 * This class enables selective injection based on boolean values stored in
 * provided shared preferences. Add the library containing this class to your
 * app module to enable feature selector.
 * <p>
 * <p>
 * ### Scope dependencies
 * `@Classifier(FEATURE_SELECTOR) preferences: SharedPreferences`
 * <p>
 * ### Scoping
 * any scoping
 */
@Instance(
        type = SelectorFilter.class,
        classifier = FEATURE_SELECTOR
)
public class FeaturesSelectorFilter extends SelectorFilter {

    private final Preferences preferences;

    public FeaturesSelectorFilter(Preferences preferences) {
        this.preferences = preferences;
    }

    public boolean filter(String[] selector) {
        if (selector.length != 4) {
            throw new IllegalStateException("Expected selector length 4, actual: " + selector.length);
        } else {
            String slc2 = selector[2];
            Operator operator;
            if (slc2.equals("==")) {
                operator = Equal.getInstance();
            } else if (slc2.equals("!=")) {
                operator = NotEqual.getInstance();
            } else {
                throw new IllegalStateException("Supported operators == and !=, actual: " + slc2);
            }
            return operator.apply(selector[1], Boolean.parseBoolean(selector[3]), preferences);
        }
    }
}
